using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class YardShipSelectList : MonoBehaviour
{
    public List<YardShipSelectItem> m_Items = new List<YardShipSelectItem>();
    public YardPanel m_Yard;
    public YardShipSelectItem m_ItemPrefab;
    public GameObject m_Content;
    public WeaponSlotSelectBoard m_SelectBoardPrefab;
    List<WeaponSlotSelectBoard> m_WeaponSlotBoards = new List<WeaponSlotSelectBoard>();

    void Start()
    {
         
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void Init(Player player)
    {
        Clear();
        foreach (var i in player.ships)
        {
            var item = Instantiate(m_ItemPrefab);
            item.Init(i, this);
            item.transform.SetParent(m_Content.transform);
            item.transform.SetSiblingIndex(m_Content.transform.childCount - 2);
            m_Items.Add(item);
        }
    }
    void Clear()
    {
        foreach(var i in m_Items)
        {
            Destroy(i.gameObject);
        }
        m_Items.Clear();
    }
    public void OnItemSelected(YardShipSelectItem item)
    {
        if (item.ship == m_Yard.selectedShip && m_Yard.selectedShip != null)
            return;
        if (m_Yard.selectedShip != null)
        {
            m_Yard.selectedShip.gameObject.SetActive(false);
            m_Yard.selectedShip.ClearShipUI();
        }
        m_Yard.InitShip(item.ship);

        var ship  = item.ship;
        if (ship == null)
            return;
        Controler.Instance.FocusShip(ship);

        ClearWeaponSlotBoards();
        GenerateWeaponSlotBoards(ship);
    }

    public void ClearWeaponSlotBoards()
    {
        foreach (var i in m_WeaponSlotBoards)
        {
            Destroy(i.gameObject);
        }
        m_WeaponSlotBoards.Clear();
    }
    public void GenerateWeaponSlotBoards(Ship ship)
    {
        foreach (var i in ship.m_WeaponSlots)
        {
            var theNewBoared = Instantiate(m_SelectBoardPrefab);
            theNewBoared.m_Warehouse = ship.m_Warehouse;
            theNewBoared.Init(i);
            theNewBoared.transform.SetParent(Utils.GetCanvas().transform);
            m_WeaponSlotBoards.Add(theNewBoared);
        }
    }
}
